package com.baomidou.springmvc.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springmvc.common.result.RequestDTO;
import com.baomidou.springmvc.common.result.ServerResponse;
import com.baomidou.springmvc.exception.myexception.ServiceException;
import com.baomidou.springmvc.model.dto.DrawPrizeRecordDTO;
import com.baomidou.springmvc.model.enums.PrizeTimeEnum;
import com.baomidou.springmvc.model.enums.PrizeTypeEnum;
import com.baomidou.springmvc.model.system.DrawPrizeRecord;
import com.baomidou.springmvc.model.system.Prize;
import com.baomidou.springmvc.service.system.IDrawPrizeRecordService;
import com.baomidou.springmvc.service.system.IPrizeService;

@Controller
@RequestMapping("prize")
public class PrizeController extends BaseController{
	
	private static Logger LOGGER = LoggerFactory.getLogger(PrizeController.class);
	
	@Autowired
	private IPrizeService prizeService;
	
	@Autowired
	private IDrawPrizeRecordService drawPrizeRecordService;
	
	@ResponseBody
    @RequestMapping(value="/save",method=RequestMethod.POST)
    public ServerResponse<Prize> save(@RequestBody Prize prize) {
		if(PrizeTypeEnum.UTR.getValue()==prize.getType()) {
			prize.setDesc(PrizeTypeEnum.UTR.getDesc());
		}else if(PrizeTypeEnum.SSR.getValue()==prize.getType()) {
			prize.setDesc(PrizeTypeEnum.SSR.getDesc());
		}else if(PrizeTypeEnum.SR.getValue()==prize.getType()) {
			prize.setDesc(PrizeTypeEnum.SR.getDesc());
		}else if(PrizeTypeEnum.R.getValue()==prize.getType()) {
			prize.setDesc(PrizeTypeEnum.R.getDesc());
		}else if(PrizeTypeEnum.N.getValue()==prize.getType()) {
			prize.setDesc(PrizeTypeEnum.N.getDesc());
		}
		prize.setUpdatetime(new Date());
        if (prize.getId() == null) {
        	prize.setCreatetime(new Date());
            return prizeService.insert(prize) ? ServerResponse.createBySuccess("添加成功",prize) : ServerResponse.createByErrorMessage("添加失败");
        } else {
            return prizeService.updateById(prize) ? ServerResponse.createBySuccess("修改成功",prize) : ServerResponse.createByErrorMessage("修改失败");
        }
    }
	
	@ResponseBody
    @RequestMapping(value="/getPrizeRecord",method=RequestMethod.POST)
	ServerResponse<DrawPrizeRecordDTO> getPrizeRecordByOpenId(@RequestParam String openId){
		LOGGER.error("++++++++++openId++++++++"+openId);
		DrawPrizeRecordDTO drawPrizeRecord = drawPrizeRecordService.getRecord(openId);
		if(null!=drawPrizeRecord) {
			LOGGER.error("++++++++++id++++++++++++"+drawPrizeRecord.getId());
		}
		
		return ServerResponse.createBySuccess("获取奖品记录成功", drawPrizeRecord);
	}
	
	
	@ResponseBody
    @RequestMapping(value="/getPrize",method=RequestMethod.POST)
	//public ServerResponse<Map<String,Object>> getPrize(@RequestBody RequestDTO requestDTO ) throws ParseException {
	public ServerResponse<Map<String,Object>> getPrize(@RequestParam String openId ) throws ParseException {	
		Map<String,Object> resultMap = new HashMap<String,Object>(); 
		//String  time= requestDTO.getParam("time");
		//String openId = requestDTO.getParam("openId");
		//LOGGER.info("**********time="+time);
		LOGGER.info("**********openId="+openId);
		//long nowtime = new Date().getTime();
		//long timeL = Long.parseLong(time);
		long timeL = new Date().getTime();
		long nowtime = timeL;
		long day14s = sdf.parse(PrizeTimeEnum.day14.getStarttime()).getTime();
		long day14e = sdf.parse(PrizeTimeEnum.day14.getEndtime()).getTime();
		
		long day15s = sdf.parse(PrizeTimeEnum.day15.getStarttime()).getTime();
		long day15e = sdf.parse(PrizeTimeEnum.day15.getEndtime()).getTime();
		
		long day16s = sdf.parse(PrizeTimeEnum.day16.getStarttime()).getTime();
		long day16e = sdf.parse(PrizeTimeEnum.day16.getEndtime()).getTime();
		
		long day17s = sdf.parse(PrizeTimeEnum.day17.getStarttime()).getTime();
		long day17e = sdf.parse(PrizeTimeEnum.day17.getEndtime()).getTime();
		
		long day18s = sdf.parse(PrizeTimeEnum.day18.getStarttime()).getTime();
		long day18e = sdf.parse(PrizeTimeEnum.day18.getEndtime()).getTime();
		
		/**
		 * 判断是不是在活动期间
		 */
		if(!((day14s<=timeL&&timeL<=day14e)||(day15s<=timeL&&timeL<=day15e)||(day16s<=timeL&&timeL<=day16e)||(day17s<=timeL&&timeL<=day17e)||(day18s<=timeL&&timeL<=day18e))) {
			return  ServerResponse.createByErrorMessage("不在活动期间哦");
		}
		
		/**
		 * 判断是不是已经抽过奖
		 */
		DrawPrizeRecordDTO drawPrizeRecord = drawPrizeRecordService.getRecord(openId);
		if(null!=drawPrizeRecord) {
			return ServerResponse.createByErrorMessage("每位用户抽奖只限一次哦");
		}
		
		
		List<Prize> prizeList = prizeService.findList();
		//公平获取奖品代号
		int randN = prizeService.getPrizeIndex(prizeList);
		//经过自定义规则后的奖品代号
		int finallyRandN = prizeService.getFinallyPrizeIndex(prizeList, randN, nowtime, day14s, day14e, day15s, day15e, day16s, day16e, day17s, day17e, day18s, day18e, openId);
		//将奖品代号再转成前端设置的奖品代号
		int jspPrizeIndex = prizeService.getJspPrizeIndex(finallyRandN);
		resultMap.put("prizeIndex", jspPrizeIndex);
		//查询中奖对换码
		DrawPrizeRecordDTO drawPR= drawPrizeRecordService.getRecord(openId);
		if(null==drawPR) {
			throw new ServiceException("未查询到中奖信息");
		}
		resultMap.put("exchangeNum",drawPR.getId().toString());
		
		return ServerResponse.createBySuccess("抽奖成功",resultMap);
    }
	
	@ResponseBody
    @RequestMapping(value="/exchange",method=RequestMethod.POST)
	ServerResponse<Object> exchange(@RequestParam String id){
		LOGGER.info("*************id********"+id);
		DrawPrizeRecord dpr = drawPrizeRecordService.selectById(Long.valueOf(id));
		if(null == dpr) {
			return ServerResponse.createByErrorMessage("未查到中奖信息");
		}
		dpr.setIsExchange(PrizeTypeEnum.DONE_EXCHANGE.getVal());
		drawPrizeRecordService.updateById(dpr);
		return ServerResponse.createBySuccessMessage("奖品领取成功");
	}
	
	@RequestMapping("/listPrize")
	public ModelAndView listPrize(ModelAndView modelAndView) {
		List<Prize> prizeList = prizeService.findList();
		modelAndView.setViewName("prize_list");
		modelAndView.addObject("prizeList", prizeList);
		return modelAndView;
	}
	
	@RequestMapping("/listPrizeRecord")
	public ModelAndView listPrizeRecord(ModelAndView modelAndView) {
		List<DrawPrizeRecordDTO> drawPrizeRecordDTOList = drawPrizeRecordService.getAllRecord();
		modelAndView.setViewName("prize_record");
		modelAndView.addObject("prizeRecordList", drawPrizeRecordDTOList);
		return modelAndView;
	}
	
	@RequestMapping("/preSave")
	public ModelAndView preSave(ModelAndView modelAndView, @RequestParam(value = "id", required = false) Long id) {
		 modelAndView.setViewName("prize_edit");
	        if (id != null) {
	            modelAndView.addObject("prize", prizeService.selectById(id));
	        }
	        return modelAndView;
	}
	
	@RequestMapping("/saveEdit")
	@ResponseBody
	public ServerResponse<Object> saveEdit(@RequestBody Prize prize) {
//		String id = requestDTO.getParam("id");
//		String name =requestDTO.getParam("name");
//		String weight =requestDTO.getParam("weight");
//		String day14 =requestDTO.getParam("day14");
//		String day15 =requestDTO.getParam("day15");
//		String day16 =requestDTO.getParam("day16");
//		String day17 =requestDTO.getParam("day17");
//		String day18 =requestDTO.getParam("day18");
		if(!prizeService.updateById(prize)) {
			return ServerResponse.createByErrorMessage("修改信息失败");
		}
		return ServerResponse.createBySuccessMessage("修改信息成功");
	}

}
